﻿using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {

	public GUIStyle box_style;
	
	public static float hp = 20;
	public static float max_hp = 20;
	public GUIStyle hp_style;
	
	public static float charge = 40;
	public static float max_charge = 40;
	public GUIStyle charge_style;
	
	public Vector3 start_pos;
	
	void Start()
	{
		start_pos = transform.position;
	}
	public void ResetStats()
	{
		hp = max_hp;
		charge = max_charge;
		
		gameObject.GetComponent<PlayerMovement>().disable_movement = false;
		gameObject.GetComponentInChildren<PlayerShooting>().ResetGunLevel(3);
		
		transform.position = start_pos;
	}
	public void ReduceHP(float amount)
	{
		hp -= amount;
	}
	public void ReduceCharge(float amount)
	{
		charge -= amount;
	}
	
	// Update is called once per frame
	void OnGUI () {
	
		float w_mul = 2f;
		
		float w = (hp/max_hp) * max_hp * w_mul;
		GUI.Box (new Rect(0,0,max_hp*w_mul,16),"",box_style);
		GUI.Box (new Rect(0,0,w,16),"",hp_style);
		
		w_mul = 1f;
		w = (charge/max_charge) * max_charge * w_mul;
		GUI.Box (new Rect(0,16,max_charge*w_mul,16),"",box_style);
		GUI.Box (new Rect(0,16,w,16),"",charge_style);
	}
	void Update()
	{
		//hp += Time.deltaTime;
		
		if(hp > max_hp)
			hp = max_hp;
		if(hp <= 0)
			gameObject.GetComponent<PlayerMovement>().disable_movement = true;
			//Destroy (gameObject);
		
		if(charge > max_charge)
			charge = max_charge;
		if(charge <= 0)
			charge = 0;
			
			
	}
	void OnTriggerEnter2D(Collider2D c)
	{
		//print (c.gameObject.tag);
		
		if(c.gameObject.tag == "Collectable")
		{
			if(c.gameObject.GetComponent<Collectable>().is_pwup == true)
				gameObject.GetComponentInChildren<PlayerShooting>().AddGunLevel();
			else
				if(c.gameObject.GetComponent<Collectable>().is_health == true)
					hp += 10.0f;
			else
				if(c.gameObject.GetComponent<Collectable>().is_hpup == true)
			{
				max_hp += 2.5f;
				hp += 2.5f;
			}
			else
				if(c.gameObject.GetComponent<Collectable>().is_chup == true)
			{
				max_charge += 5.0f;
				charge += 5.0f;
			}
			else
				charge += 10.0f;
				
			Destroy(c.gameObject);
		}	
		else	
			if(c.gameObject.tag == "Finish")
		{
			Application.LoadLevel(Application.loadedLevelName);
			//c.GetComponent<fade>().start_by_external=false;
		}	
		
	}
	void OnCollisionEnter2D(Collision2D c)
	{
		//print (c.gameObject.tag);
		
		if(c.gameObject.tag == "Bullet")
		{
			Bullet bullet = c.gameObject.GetComponent<Bullet>();
			
			if(bullet.shooter != "Player")
				hp-=bullet.damage;
		}
	}
}
